package com.faithbj.common.utils;

import java.util.Date;

import javax.annotation.Resource;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import com.faithbj.common.dao.SystemLogInfoDao;
import com.faithbj.common.dao.UserLogInfoDao;
import com.faithbj.common.model.SystemLogInfo;
import com.faithbj.common.model.User;
import com.faithbj.common.model.UserLogInfo;

/**
 * @author jrn E-mail: rinanjin@gmail.com
 * @version 0.1 
 * 创建时间：2012-6-25 下午09:44:03
 * 类说明
 */
@Component("logUtil")
public class LogUtil
{
	@Resource(name = "userLogInfoDao")
	private UserLogInfoDao userLogInfoDao;
	
	@Resource(name = "systemLogInfoDao")
	private SystemLogInfoDao systemLogInfoDao;
	
	public void logUserLogInfo(User user, String operation)
	{
		UserLogInfo userLogInfo = new UserLogInfo();
		userLogInfo.setUsername(user.getUsername());
		userLogInfo.setOperateDate(new Date());
		userLogInfo.setOperation(operation);
		userLogInfo.setRegion(user.getRegion());
		userLogInfoDao.save(userLogInfo);
	}
	
	public void logUserLogInfo(String operation)
	{
		UserLogInfo userLogInfo = new UserLogInfo();
		Object userObject = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		if (userObject instanceof User)
		{
			User user = (User)userObject;
			userLogInfo.setUsername(user.getUsername());
			userLogInfo.setOperateDate(new Date());
			userLogInfo.setOperation(operation);
			userLogInfo.setRegion(user.getRegion());
			userLogInfoDao.save(userLogInfo);
			userLogInfoDao.flush();
		}
		else
		{
			return;
		}
	}
	
	public void logSystemLogInfo(String operation, String errorMessage)
	{
		SystemLogInfo systemLogInfo = new SystemLogInfo();
		Object userObject = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		if (userObject instanceof User)
		{
			User user = (User)userObject;
			systemLogInfo.setOperation(operation);
			systemLogInfo.setErrorMessage(errorMessage);
			systemLogInfo.setUsername(user.getUsername());
			systemLogInfo.setRegion(user.getRegion());
			systemLogInfoDao.save(systemLogInfo);
			systemLogInfoDao.flush();
		}
		else
		{
			return;
		}
	}
}
